package com.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.commonutils.RandomUtil;
import com.commonutils.results;
import com.entity.pojo.Categories;
import com.entity.pojo.Concept;
import com.entity.pojo.Courses;
import com.entity.vo.ConceptVo;
import com.entity.vo.CourseOverviewVo;
import com.service.CategoriesService;
import com.service.ConceptService;
import com.utils.InitData;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenmo
 * @since 2022-04-02
 */
@RestController
@RequestMapping("/categories")
@CrossOrigin
public class CategoriesController {
    @Resource
    private CategoriesService categoriesService;

    @Resource
    private InitData initData;

    @Resource
    private ConceptService conceptService;

    @ApiOperation("组合条件查询每门课程下对应的目录数")
    @PostMapping("/getCourseOverview/{current}/{limit}")
    public results getCourseOverviewsPageCondition(@PathVariable long current,
                                                   @PathVariable long limit,
                                                   @RequestBody(required = false) CourseOverviewVo CourseOverviewQuery) {
        List<CourseOverviewVo> courseOverviewList = categoriesService.getCourseOverview(current, limit, CourseOverviewQuery);
        int total = courseOverviewList.size();
        return results.ok().data("courseOverviewList", courseOverviewList).data("total", total);
    }

    @ApiOperation("组合条件查询目录信息")
    @PostMapping("/pageCategoriesCondition/{current}/{limit}")
    public results pageCategoriesCondition(@PathVariable long current,
                                           @PathVariable long limit,
                                           @RequestBody(required = false) Categories category) {
        Page<Categories> pageCategory = new Page<>(current, limit);
        QueryWrapper<Categories> categoryWrapper = new QueryWrapper<>();
        validateCondition(categoryWrapper, category);
        categoryWrapper.orderByAsc("positionId");
        categoriesService.page(pageCategory, categoryWrapper);
        long total = pageCategory.getTotal();
        List<Categories> categoryList = pageCategory.getRecords();
        return results.ok().data("categoryList", categoryList).data("total", total);
    }

    @ApiOperation("拖拽改变目录次序")
    @PostMapping("/updateCategoryPosition/{newIndex}")
    public results updateCategoryPosition(@PathVariable Integer newIndex,
                                          @RequestBody Categories currRow) {
        return categoriesService.updateCategoryPosition(newIndex + 1, currRow);
    }

    @ApiOperation("根据课程id查询对应的目录信息")
    @GetMapping("/getCategoriesInfoByCourseId/{courseId}")
    public results getCategoriesInfoByCourseId(@PathVariable Integer courseId) {
        List<Categories> twoCategoryIdAndNameList = categoriesService
                .list(new QueryWrapper<Categories>()
                        .eq("courseId", courseId)
                        .select("categoryId", "categoryName"));
        return results.ok().data("twoCategoryIdAndNameList", twoCategoryIdAndNameList);
    }

    @ApiOperation("查询所有的课程名称和id")
    @GetMapping("/getCategoriesIdAndName")
    public results getCategoriesIdAndName() {
        List<Categories> allCoursesIdAndNameList = categoriesService.list(new QueryWrapper<Categories>()
                .select("categoryId", "categoryName"));
        return results.ok().data("allCoursesIdAndNameList", allCoursesIdAndNameList);
    }

    private void validateCondition(QueryWrapper<Categories> wrapper, Categories category) {
        Integer courseId = category.getCourseId();
        String categoryName = category.getCategoryName();
        String courseName = category.getCourseName();
        String nextCategoryStr = category.getNextCategoryStr();
        String propertiesKey = category.getPropertiesKey();
        String propertiesValue = category.getPropertiesValue();
        String createdByName = category.getCreatedByName();

        if (courseId != null) {
            wrapper.eq("courseId", courseId);
        }
        if (StringUtils.hasText(categoryName))
            wrapper.like("categoryName", categoryName);
        if (StringUtils.hasText(courseName))
            wrapper.like("courseName", courseName);
        if (StringUtils.hasText(nextCategoryStr))
            wrapper.like("nextCategoryStr", nextCategoryStr);
        if (StringUtils.hasText(propertiesKey))
            wrapper.like("propertiesKey", propertiesKey);
        if (StringUtils.hasText(propertiesValue))
            wrapper.like("propertiesValue", propertiesValue);
        if (StringUtils.hasText(createdByName))
            wrapper.like("createdByName", createdByName);
    }

    @ApiOperation("增加新的目录")
    @PostMapping("addCategory")
    public results addCategory(@RequestBody Categories category) {
        if (category.getCourseId() == null) {
            return results.error("添加失败，需要先指定课程，才能增加新的目录信息！");
        }
        if (!StringUtils.hasText(category.getCategoryName())) {
            return results.error("添加失败，目录名称不能为空");
        }
        initData.initCategory(category);
        boolean saveFlag = categoriesService.save(category);
        if (saveFlag) {
            return results.ok();
        } else {
            return results.error("未知错误，添加新的目录信息失败");
        }
    }

//    private void initInfo(Categories category) {
//        // 设置排序字段值
//        List<Categories> list = categoriesService.list(new QueryWrapper<Categories>()
//                .eq("courseId", category.getCourseId())
//                .select("positionId"));
//        int maxPositionId;
//        if (list.isEmpty()) {
//            maxPositionId = 1;
//        } else {
//            maxPositionId = list.stream().mapToInt(Categories::getPositionId).summaryStatistics().getMax();
//        }
//        category.setPositionId(maxPositionId + 1);
//        // 设置目录代码
//        QueryWrapper<Categories> wrapper = new QueryWrapper<Categories>().select("max(categoryId) as categoryId");
//        Categories categories = categoriesService.getOne(wrapper);
//        int maxPrimaryId = categories == null ? 1 : categories.getCategoryId();
//        StringBuilder maxPrimaryIdStr = new StringBuilder(Integer.toString(maxPrimaryId));
//        while (maxPrimaryIdStr.length() < 5) {
//            maxPrimaryIdStr.insert(0, "0");
//        }
//        String categoryCode = "A" + RandomUtil.getSixBitRandom() + maxPrimaryIdStr;
//        category.setCategoryCode(categoryCode);
//    }

    @ApiOperation("修改课程信息")
    @PutMapping("updateCategory")
    public results updateCategory(@RequestBody Categories category) {
        boolean updateFlag = categoriesService.updateById(category);
        if (updateFlag) {
            return results.ok();
        } else {
            return results.error("修改目录信息失败");
        }
    }

    @ApiOperation("删除目录")
    @DeleteMapping("deleteCategories/{categoryId}")
    public results deleteCategories(@PathVariable Integer categoryId) {
        int count = conceptService.count(new QueryWrapper<Concept>().eq("categoryId", categoryId));
        if (count != 0) {
            return results.error("请先删除该目录下的知识点，再删除该目录！");
        }
        boolean removeFlag = categoriesService.removeById(categoryId);
        if (removeFlag) {
            return results.ok();
        } else {
            return results.error("删除目录失败");
        }
    }
}

